package com.wt.springboot.demo.custom.components.requestmonitor;

import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author wangtao
 * @date 2023/3/11 10:53
 **/
@ControllerAdvice
public class RequestMonitorResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 如果返回体是RequestMonitor的子类，就返回true
        return RequestMonitor.class.isAssignableFrom(returnType.getMethod().getReturnType());
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 获取计时器
        StopWatch watch = RequestMonitorContextHolder.get();
        // 停掉耗时监控
        watch.stop();
        // 统一给返回体设置traceId和耗时
        RequestMonitor rm = (RequestMonitor) body;
        rm.setTraceId(TraceUtil.getTraceId());
        rm.setTimeUse(watch.getTotalTimeMillis());
        return body;
    }

}
